package com.novel.resource.oss.autoConfigurer;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.novel.resource.oss.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * oss 客户端工厂
 *
 * @author novel
 * @date 2019/6/4
 */
@Slf4j
public class OssClientFactoryBean implements FactoryBean<OSS>, InitializingBean, DisposableBean {
    private OSS ossClient;
    private OssConfig ossConfig;

    public OssClientFactoryBean(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public OSS getObject() throws Exception {
        return this.ossClient;
    }

    @Override
    public Class<?> getObjectType() {
        return OSS.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        if (this.ossClient != null) {
            this.ossClient.shutdown();
            log.info("OSS 销毁...");
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 创建OSSClient实例。
        log.info("OSS 初始化...");
        ossClient = new OSSClientBuilder().build(ossConfig.getOssEndpoint(), ossConfig.getOssAccessKeyId(), ossConfig.getOssAccessKeySecret());
        if (!ossClient.doesBucketExist(ossConfig.getBucketName())) {
            ossClient.createBucket(ossConfig.getBucketName());
        }
    }
}
